﻿using lwzlz.Application.System.Dto;
using lwzlz.Core;
using lwzlz.Core.Repository;
using System.Collections.Generic;
using System.Linq;

namespace lwzlz.Application.System
{
    public class UserRoleTBService
    {
        private readonly IRepository<UserRole> _repository;

        public UserRoleTBService()
        {
            _repository = new Repository<UserRole>();
        }

        #region 获取用户的权限
        /// <summary>
        /// 获取用户的权限
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public IEnumerable<UserLoginRole> GetUserRoleList(int Id)
        {
            return _repository.Query<UserLoginRole>("select RoleId, RoleCode,RoleName FROM Sys_UserRole left join Sys_Role r on r.Id = RoleId WHERE UserId=@UserId",
                new { @UserId = Id });
        }
        #endregion

        #region 获取用户的角色权限列表
        public IEnumerable<UserRoleOutput> GetRoleList(int Id)
        {
            var AllList = new RoleService().GetList();
            var List = _repository.Query<UserRole>("SELECT * FROM Sys_UserRole WHERE UserId=@UserId",
                new { @UserId = Id });
            IEnumerable<UserRoleOutput> roles = AllList.Select((role, p) =>
                new UserRoleOutput
                {
                    Id = role.Id,
                    RoleName = role.RoleName,
                    IsEnable = List.Where(ur => ur.RoleId == role.Id).Count() > 0
                });
            return roles;
        }
        #endregion

        #region 添加
        public int? Add(UserRole model)
        {
            return _repository.Insert(model);
        }
        #endregion

        #region 获得对象
        public UserRole GetRole(int Id, int RoleId)
        {
            return _repository.QueryFirstOrDefault("select * from Sys_UserRole where UserId=@UserId and RoleId=@RoleId",
                new { @UserId = Id, @RoleId = RoleId });
        }
        #endregion

        #region 删除
        public int? Delete(UserRole model)
        {
            return _repository.Delete(model);
        }
        #endregion
    }
}
